package cn.wolfcode.exception;

import cn.wolfcode.vo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 杨兴健
 * @Date 2020/7/16 10:04
 */
@ControllerAdvice
public class UniteExceptionHandler {

    @ExceptionHandler(Exception.class)
    public String exception(Exception ex, HttpServletResponse response, HandlerMethod handlerMethod) {
        ex.printStackTrace();
        if (handlerMethod.hasMethodAnnotation(ResponseBody.class)) {
            response.setContentType("application/json;charset=utf-8");
            try {
                response.getWriter().println(JSON.toJSONString(new JsonResult(false, "发生了错误：" + ex.getMessage() + ",请联系管理员")));
                return null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "common/error";
    }

    @ExceptionHandler(LogicException.class)
    @ResponseBody
    public JsonResult logicException(LogicException e) {
        e.printStackTrace();
        return new JsonResult(false, e.getMessage());
    }

    @ExceptionHandler(UnauthorizedException.class)
    public String unauthorizedException(UnauthorizedException e, HttpServletResponse response, HandlerMethod handlerMethod) {
        e.printStackTrace();
        if (handlerMethod.hasMethodAnnotation(ResponseBody.class)) {
            response.setContentType("application/json;charset:utf-8");
            try {
                response.getWriter().println(JSON.toJSONString(new JsonResult(false, e.getMessage())));
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            return null;
        }
        return "common/nopermission";
    }

}
